package com.zyylr.classroomreservationsystem.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.bean.LoginUser;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.bean.User;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;
import com.zyylr.classroomreservationsystem.web.IUserLogin;

import org.jetbrains.annotations.NotNull;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.omidh.ripplevalidatoredittext.RVEValidatorFactory;
import me.omidh.ripplevalidatoredittext.RVEValidatorType;
import me.omidh.ripplevalidatoredittext.RippleValidatorEditText;
import me.omidh.ripplevalidatoredittext.validator.RVEValidator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends MyBaseCompatActivity {

    private RippleValidatorEditText userName;
    private RippleValidatorEditText password;
    private PullRefreshLayout pullRefreshLayout;
    private Button loginBtn;
    Retrofit retrofit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //TODO：判断用户的登录状态，已登录未过期跳转主界面，未登录或登录已过期跳转登录界面
        setContentView(R.layout.activity_main);

        userName = findViewById(R.id.editText_username);
        password = findViewById(R.id.editText_passwd);
        loginBtn = findViewById(R.id.button_login);
        pullRefreshLayout = findViewById(R.id.swipeRefreshLayout_main);
        addValidator();
        addListener();
        loginBtn.setClickable(false);
        loginBtn.setBackgroundResource(R.drawable.shape_button_validator_freetime);

//        pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP);
//        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                pullRefreshLayout.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        sendHttpRequest();
//                    }
//                },0);
//            }
//        });
//        pullRefreshLayout.setRefreshing(true);
//        sendHttpRequest();

        //使界面顶部沉浸式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //给状态栏设置颜色。我设置透明。
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 为用户名和密码两个editText添加校验
     */
    private void addValidator() {
        userName.addValidator(
                RVEValidatorFactory.getValidator(RVEValidatorType.MIN_LENGTH, "最少7个数字", 7),
                RVEValidatorFactory.getValidator(RVEValidatorType.EMPTY, "账号不能为空", null),
                new RVEValidator("账号必须全为数字") {
                    @Override
                    public boolean isValid(@NonNull CharSequence text) {
                        Pattern pattern = Pattern.compile("[0-9]*");
                        Matcher isNum = pattern.matcher(text.toString());
                        return isNum.matches();
                    }
                }
        );
        password.addValidator(
                RVEValidatorFactory.getValidator(RVEValidatorType.EMPTY, "密码不能为空", null)
        );
    }

    /**
     * 登录按钮添加监听器
     * 用户名和密码输入框添加输入监听，当输入正确时设置按钮可点击
     */
    private void addListener() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Retrofit retrofit = RetrofitFactory.getRetrofit();
                IUserLogin request = retrofit.create(IUserLogin.class);
                Call<Msg<User>> msgCall = request.getLoginCall(userName.getText().toString(), password.getText().toString());

                //异步调用
                msgCall.enqueue(new Callback<Msg<User>>() {
                    @Override
                    public void onResponse(Call<Msg<User>> call, Response<Msg<User>> response) {
                        Msg msg = response.body();
                        Log.d("web", "msg:" + msg);
                        try {
                            assert msg != null;
                            //登录错误，toast错误信息
                            if (msg.getCode() == 200) {
                                Toast.makeText(getApplicationContext(), msg.getMsg(), Toast.LENGTH_SHORT).show();
                                return;
                            }
                            //登录成功，跳转界面
                            User user = (User) msg.getExtend().get("user");
                            Log.d("web", "user:" + user);
                            //创建一个登录的用户实例对象
                            LoginUser.login(user);
                            Intent intent = null;
                            assert user != null;
                            if (user.getRole() == User.ROLE_COMMON) {
                                intent = new Intent(MainActivity.this, CommonUserActivity.class);
                            } else if (user.getRole() == User.ROLE_AUDIT_ADMIN) {
                                intent = new Intent(MainActivity.this, AuditAdminActivity.class);
                            } else if (user.getRole() == User.ROLE_DATA_ADMIN) {
                                intent = new Intent(MainActivity.this, DataAdminActivity.class);
                            }
                            //assert intent != null;
                            intent.putExtra("user", user);
                            startActivity(intent);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "数据解析错误！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Call<Msg<User>> call, @NotNull Throwable t) {
                        Toast.makeText(getApplicationContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        userName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (userName.isValid(false) && password.isValid(false)) {
                    loginBtn.setClickable(true);
                    loginBtn.setBackgroundResource(R.drawable.shape_button_validator);
                } else {
                    loginBtn.setClickable(false);
                    loginBtn.setBackgroundResource(R.drawable.shape_button_validator_freetime);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (userName.isValid(false) && password.isValid(false)) {
                    loginBtn.setClickable(true);
                    loginBtn.setBackgroundResource(R.drawable.shape_button_validator);
                } else {
                    loginBtn.setClickable(false);
                    loginBtn.setBackgroundResource(R.drawable.shape_button_validator_freetime);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

}
